//
//  NASubNavigationController.m
//  nanavigation
//
//  Created by zhangyue on 16/4/6.
//  Copyright © 2016年 zeroflow. All rights reserved.
//

#import "NASubNavigationController.h"
#import "UIViewController+NANav.h"
@interface NASubNavigationController ()<UINavigationControllerDelegate,UIGestureRecognizerDelegate>
@property (strong ,nonatomic) UIPanGestureRecognizer *backPanGesture;
@property (strong ,nonatomic) id backGestureRecognizerDelegate;
@end

@implementation NASubNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;
    
    self.backGestureRecognizerDelegate = self.interactivePopGestureRecognizer.delegate;
    self.backPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.backGestureRecognizerDelegate action:NSSelectorFromString(@"handleNavigationTransition:")];
    self.backPanGesture.delegate = self;
    self.backPanGesture.maximumNumberOfTouches = 1;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)setViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers{
    [super setViewControllers:viewControllers];
    if (viewControllers.count == 1) {
        [self.view removeGestureRecognizer:self.backPanGesture];
        if (self.na_delegate && [self.na_delegate respondsToSelector:@selector(switchMainNavBackPanEnable:)]) {
            [self.na_delegate switchMainNavBackPanEnable:YES];
        }
    } else {
        [self.view addGestureRecognizer:self.backPanGesture];
    }
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.na_delegate && [self.na_delegate respondsToSelector:@selector(didSubNavShowViewController:)]) {
        [self.na_delegate didSubNavShowViewController:viewController];
    }
    if (self.na_delegate && [self.na_delegate respondsToSelector:@selector(switchMainNavBackPanEnable:)]) {
        [self.na_delegate switchMainNavBackPanEnable:viewController.navigationController.viewControllers.count == 1];
    }
    
    if (self.viewControllers.count == 1) {
        [self.view removeGestureRecognizer:self.backPanGesture];
    } else {
        [self.view addGestureRecognizer:self.backPanGesture];
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    CGPoint point = [touch locationInView:self.view];
    return point.x < 25;
}

@end
